package main

import (
	"context"
	"fmt"
	"go_stu/5_grpc_stu/7_grpc_auth/protos"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type customCredential struct{}

func (c *customCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"appid":  "10101011",
		"appkey": "i am key imooc",
	}, nil
}
func (c *customCredential) RequireTransportSecurity() bool {
	return false
}

func main() {
	// 客户端拦截器
	/*interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		start := time.Now()

		// 创建meta数据
		md := metadata.New(map[string]string{
			"appid":  "10101011 1",
			"appkey": "i am key imooc",
		})
		ctx = metadata.NewOutgoingContext(context.Background(), md)
		err := invoker(ctx, method, req, reply, cc, opts...)
		fmt.Printf("耗时：%s\n", time.Since(start))
		return err
	}*/

	// opt := grpc.WithUnaryInterceptor(interceptor)

	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	// 方式1
	// opts = append(opts, grpc.WithUnaryInterceptor(interceptor))
	// 方式2
	opts = append(opts, grpc.WithPerRPCCredentials(&customCredential{}))

	conn, err := grpc.Dial("127.0.0.1:8083", opts...)
	if err != nil {
		panic(err.Error())
	}
	defer conn.Close()
	c := protos.NewGreeterClient(conn)
	// 超时控制
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	r, err := c.SayHello(ctx, &protos.HelloRequest{Name: "Boby"})
	if err != nil {
		panic(err.Error())
	}
	fmt.Println(r.Message)
}
